package com.bigzero.workflow.modules.process.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bigzero.workflow.common.exception.WorkflowException;
import com.bigzero.workflow.modules.process.dao.ListenerDao;
import com.bigzero.workflow.modules.process.entity.ListenerEntity;
import com.bigzero.workflow.modules.process.query.ListenerQuery;
import com.bigzero.workflow.modules.process.service.ListenerService;
import com.bigzero.workflow.modules.process.vo.ListenerVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 执行监听器实现
 *
 * @author fanxinxiong
 * @email 896934834@qq.com
 * @date 2025-02-14 22:18:27
 */
@Service
public class ListenerServiceImpl extends ServiceImpl<ListenerDao, ListenerEntity> implements ListenerService{

    /**
     * 执行监听器分页列表
     *
     * @param query 分页参数
     * @return 列表
     */
    @Override
    public List<ListenerVo> queryPage(ListenerQuery query) {
        return baseMapper.queryPage(query);
    }

    /**
     * 新增或者修改
     * @param entity entity实体
     * @return int
     */
    public int insertOrUpdate(ListenerEntity entity){
        if (StringUtils.isNotEmpty(entity.getListenerId())) {
            ListenerEntity listener = this.baseMapper.selectById(entity.getListenerId());
            if (listener == null) throw new WorkflowException("未知数据");
            if (listener.getIsSys() == 1) throw new WorkflowException("系统内置不能修改!");
        }

        try {
            Class.forName(entity.getJavaClass());
        } catch (ClassNotFoundException e) {
            throw new WorkflowException("类路径不存在!");
        }

        Date date = new Date();
        if(StringUtils.isEmpty(entity.getListenerId())) {
            entity.setCreateTime(date);
        }
        entity.setUpdateTime(date);
        if(StringUtils.isEmpty(entity.getListenerId())){
            return this.baseMapper.insert(entity);
        }else{
            return this.baseMapper.updateById(entity);
        }
    }

    /**
     * 通过监听器id删除
     * @param listenerId 监听器id
     * @return int
     */
    public int deleteBylistenerId(String listenerId){
        ListenerEntity listener = getById(listenerId);
        if(listener == null){
            throw new WorkflowException("未知数据");
        }
        if(listener.getIsSys() == 1){
            throw new WorkflowException("系统内置不能删除!");
        }
        removeById(listenerId);
        return 1;
    }
}
